package ar.edu.itba.it.paw.web.product;

import java.util.List;

import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.validation.AbstractFormValidator;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

import ar.edu.itba.it.paw.domain.Auction;
import ar.edu.itba.it.paw.domain.Category;
import ar.edu.itba.it.paw.domain.EntityModel;
import ar.edu.itba.it.paw.domain.Product;
import ar.edu.itba.it.paw.domain.User;
import ar.edu.itba.it.paw.repo.CategoryRepo;
import ar.edu.itba.it.paw.web.base.BasePage;

public class EditProductPage extends BasePage {

	@SpringBean
	CategoryRepo categoryRepo;
	
	public EditProductPage(Product product){
		
		setDefaultModel(new CompoundPropertyModel<Product>(new EntityModel<Product>(Product.class,product)));
		
		add(new FeedbackPanel("feedback").add(new SimpleAttributeModifier("style", "color: #FF0000")));
		Form<Product> form = new Form<Product>("editProductForm", new CompoundPropertyModel<Product>(new EntityModel<Product>(Product.class,product))) {
			@Override
			protected void onSubmit() {
				
				setResponsePage(EditProductListPage.class);
			}
		};
		form.add(new TextField<String>("name").setRequired(true));
		form.add(new TextField<String>("description").setRequired(true));
		IModel<List<Category>> categoriesModel = new LoadableDetachableModel<List<Category>>() {
			@Override
			protected List<Category> load() {
				return categoryRepo.getCategories();
			}
		};
		form.add(new DropDownChoice<Category>("category", categoriesModel).setRequired(true));
		form.add(new CheckBox("state"));
		form.add(new Button("edit", new ResourceModel("edit")));
		form.add(new AbstractFormValidator() {
			
			@Override
			public void validate(Form<?> form) {
				if(EditProductPage.this.getDefaultModelObject() instanceof Auction){
					if(((Auction)EditProductPage.this.getDefaultModelObject()).isEnded()){
						form.error(getString("ended"));
						return;
					}
				}
				
			}
			
			@Override
			public FormComponent<?>[] getDependentFormComponents() {
				return null;
			}
		});
		add(form);
	}
}
